package com.see.services.impl;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.see.domain.dao.DataNucleusUtil;
import com.see.domain.model.StaticData;
import com.see.domain.model.StockDetail;
import com.see.network.api.HtmlReader;
import com.see.network.impl.HtmlReaderImpl;
import com.see.services.api.StockDetailParser;
import com.see.services.api.StockDynamicDataFetcher;

public class StockDynamicDataFetcherImpl implements StockDynamicDataFetcher {

	private StockDetailParser googleFinaceData;
	private HtmlReader htmlReader;
	private DataNucleusUtil dataNucleusUtil;
	private final String GOOGLE_BASE_URL = "https://finance.google.com/finance/info?client=ig&q=";

	public StockDynamicDataFetcherImpl() {
		dataNucleusUtil = new DataNucleusUtil();
		htmlReader = new HtmlReaderImpl();
		googleFinaceData = new StockDetailGoogleFinaceParserImpl(htmlReader);
	}

	@Override
	public StockDetail getStockDetailBySymbol(String inputSymbol) {
		String requestURL = GOOGLE_BASE_URL + inputSymbol;
		Collection<StockDetail> stockDetailCollection = googleFinaceData
				.parse(requestURL);
		// Only one record will be returned.
		StockDetail stockDetail = stockDetailCollection
				.toArray(new StockDetail[stockDetailCollection.size()])[0];

		return stockDetail;
	}

	@Override
	public List<StockDetail> getStockDetailsBySector(String sector) {
		String symbolList = "";
		String requestURL = "";
		List<StaticData> stockDataList = dataNucleusUtil
				.getRecordBySector(sector);
		Iterator iterator = stockDataList.iterator();
		while (iterator.hasNext()) {
			StaticData staticData = (StaticData) iterator.next();
			symbolList += staticData.getSymbol() + ",";
		}
		requestURL = GOOGLE_BASE_URL + symbolList;
		Collection<StockDetail> stockDetailCollection = googleFinaceData
				.parse(requestURL);
		List<StockDetail> stockDetailList = (List) stockDetailCollection;

		return stockDetailList;
	}

	@Override
	public List<StockDetail> getStockDetailsByIndustry(String industry) {
		String symbolList = "";
		String requestURL = "";
		List<StaticData> stockDataList = dataNucleusUtil
				.getRecordByIndustry(industry);
		Iterator iterator = stockDataList.iterator();
		while (iterator.hasNext()) {
			StaticData staticData = (StaticData) iterator.next();
			symbolList += staticData.getSymbol() + ",";
		}
		requestURL = GOOGLE_BASE_URL + symbolList;
		Collection<StockDetail> stockDetailCollection = googleFinaceData
				.parse(requestURL);
		List<StockDetail> stockDetailList = (List) stockDetailCollection;

		return stockDetailList;
	}

}
